package com.shop.wk.service.impl;

import com.shop.wk.service.RedisService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author 日月星辰
 * @date 2020/12/26 19:21
 * @description
 */
@Service
public class RedisServiceImpl implements RedisService {

  @Autowired
  private RedisTemplate redisTemplate;

  @Override
  public void set(String key, Object value, int seconds) {
    redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
  }

  @Override
  public Object get(String key) {
    return redisTemplate.opsForValue().get(key);
  }

  @Override
  public boolean delete(String key) {

    return redisTemplate.delete(key);
  }

  @Override
  public List<Object> getByLike(String key) {
    Set<Object> s = redisTemplate.keys(key);
    return new ArrayList<>(s);
  }

  @Override
  public void likeDeleteKey(String keys) {
    Set<String> ks = redisTemplate.keys(keys);
    redisTemplate.delete(ks);
  }

  @Override
  public void setHash(String hashKey, HashMap<String, Object> map, int seconds) {
    redisTemplate.opsForHash().putAll(hashKey, map);
    redisTemplate.expire(hashKey, seconds, TimeUnit.SECONDS);
  }

  @Override
  public HashMap<String, Object> getHash(String hashKey) {
    Map map = redisTemplate.opsForHash().entries(hashKey);
    return map.isEmpty() ? null : (HashMap<String, Object>) map;
  }

  @Override
  public Object getHash(String hashKey, String mapKey) {
    return redisTemplate.opsForHash().get(hashKey, mapKey);
  }

  @Override
  public Set<String> getHashKeys(String hashKey) {
    Set<String> reslut = redisTemplate.opsForHash().keys(hashKey);
    return reslut.isEmpty() ? null : reslut;
  }

  @Override
  public List<String> getHashValues(String hashKey) {
    List<String> reslut = redisTemplate.opsForHash().values(hashKey);
    return reslut.isEmpty() ? null : reslut;
  }

  @Override
  public void updateHash(String hashKey, String mapKey, Object mapValue) {
    redisTemplate.opsForHash().put(hashKey, mapKey, mapValue);
  }

  @Override
  public void deleteHash(String hashKey, Object... mapKeys) {
    redisTemplate.opsForHash().delete(hashKey, mapKeys);
  }

  @Override
  public boolean hasHash(String hasKey, String mapKey) {
    return redisTemplate.opsForHash().hasKey(hasKey,mapKey);
  }
}
